package com.wl.application.common.untils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.tags.RequestContextAwareTag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author wl
 * @version 1.0
 * @date 2022/6/27
 * @description: 请求工具类
 */
public class HttpUtil {


    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static String getUrl(){
        return  getRequest().getRequestURI();
                //getRequest().getRequestURL().toString();
    }
    public static String getIp(){
        return getRequest().getRemoteAddr();
    }
    public static String getLinuxIp(){
        String localIp = "127.0.0.1";
        try
        {

            out: for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces
                    .hasMoreElements();)
            {
                NetworkInterface networkInterface = interfaces.nextElement();
                //屏蔽回环接口，虚拟子接口，非正常工作接口
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp())
                {
                    continue;
                }
                String name = networkInterface.getName();
                //屏蔽本地回环网卡
                if (!name.contains("docker") && !name.contains("lo"))
                {
                    Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                    while (inetAddresses.hasMoreElements())
                    {
                        InetAddress address = inetAddresses.nextElement();
                        localIp = address.getHostAddress();
                        if (!localIp.contains("::") && !localIp.contains("0:0:") && !localIp.contains("fe80"))
                        {
                            break out;
                        }
                    }
                }
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return localIp;
    }
}
